﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Data;
using Citi.Helpers;
using Citi.RoutineBase;
using Citi.ResourceConsolidation.Domain.Utils;
using Citi.ResourceConsolidation.Domain;
using System.Configuration;
using System.Threading;
using System.Globalization;
using Citi.Import.Util;

namespace Citi.ResourceConsolidation.SchedulerUI.Matrix
{

    public class MatrixExtract : IExecutableRoutine
    {
        public static List<Resource> Resources { get; set; }
        public static List<DataValue> Values { get; set; }

        public class DataValue
        {
            public string Geid { get; set; }
            public string ManagerGeid { get; set; }
            public string GOC { get; set; }
            public string ExpenseCode { get; set; }
        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var initialsGeid = ConfigurationManager.AppSettings["InitialsGeid"].Split(';');
            Values = new List<DataValue>();

            foreach (var managerGeid in initialsGeid)
            {
                var level = 0;
                var manager = new Resource().GetByGeid(managerGeid);
                GetResourceInformation(manager, currentAction, level);
            }
        }

        public DataTable ReadHtml(string geid, bool matrix)
        {
            //var htmlSource = File.ReadAllText(DownloadFile(geid, matrix));
            var url = string.Empty;
            //var filePath = string.Empty;
            if (matrix)
                url = string.Format("http://gdir.nam.nsroot.net/Globaldir_New/GDIR_Download_Excel_Report.aspx?ReportName=DIRECT_MATRIX&Full_Name=name&Top_GEID={0}&ReportsToCount=99&Lang=ENGLISH", geid);
            //filePath = string.Format("{0}\\{1}.htm", @"\\lacbra001fs0010\DATA_GRP1\FTOOLS\Apps\Matrix\ExtractedFiles", geid);
            else
                url = string.Format("http://gdir.nam.nsroot.net/Globaldir_New/GDIR_Download_Excel_Report.aspx?ReportName=DIRECT_EMP&Full_Name=name&Top_GEID={0}&ReportsToCount=99&Lang=ENGLISH", geid);
            //filePath = string.Format("{0}\\_{1}.htm", @"\\lacbra001fs0010\DATA_GRP1\FTOOLS\Apps\Matrix\ExtractedFiles", geid);

            var webRequest = WebRequest.Create(url);

            using (var response = webRequest.GetResponse())
            using (var content = response.GetResponseStream())
            using (var reader = new StreamReader(content))
            {
                var strContent = reader.ReadToEnd();

                strContent = strContent.Replace("Employee GEID", "GEID");
                strContent = strContent.Replace("Name", "Full Name");
                strContent = strContent.Replace("GOC Code", "Primary GOC");
                strContent = strContent.Replace("GOC Description", "FTE GOC Description");
                strContent = strContent.Replace("Managed Segment Description", "Managed Segment Descr");
                strContent = strContent.Replace("City", "Work City");
                strContent = strContent.Replace("Country", "Physical Country");

                try
                {
                    return HtmlTableParser.ParseTable(strContent);
                }
                catch
                {
                    return null;
                }
            }

        }

        public void GetResourceInformation(Resource manager, ICurrentAction currentAction, int level)
        {
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("en-US");

            level++;
            if (level == 10) return;

            for (int i = 1; i <= 2; i++)
            {

                if (level < 2)
                {
                    currentAction.Description = string.Format("[{0}][Level {1}][{2} from {3}]",
                            DateTime.Now,
                            level,
                            i == 1 ? "MATRIX" : "DIRECT",
                            manager != null ? manager.FullName : "No Manager Name");
                }

                var dataTable = ReadHtml(manager.GeId, i == 1);

                if (dataTable == null) continue;

                List<Error> errors = null;
                List<Resource> resources;

                errors = ResourceUpdateDatabase.ImportResourceConsolidation(new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1), currentAction, errors, dataTable, ResourceType.Matrix, out resources);
                
                foreach (var resource in resources)
                {
                    try
                    {
                        if (level < 2)
                        {
                            currentAction.Description = string.Format("[{0}][Level {1}][Extracting {2} {3} from {4}]",
                                                        DateTime.Now,
                                                        level,
                                                        i == 1 ? "MATRIX" : "DIRECT",
                                                        resource.FullName,
                                                        manager.FullName);
                        }

                        if (i == 1)
                        {
                            var matrix = manager.MatrixReports.FirstOrDefault(x => x.ResourceId == resource.Id && x.ReferenceDate == DateTime.Today);

                            if (matrix != null) continue;

                            matrix = new MatrixHierarchy { ManagerId = manager.Id, ResourceId = resource.Id, ReferenceDate = DateTime.Today };
                            
                            matrix.Save(matrix);
                        }

                        GetResourceInformation(resource, currentAction, level);
                    }
                    catch (Exception e)
                    {
                        throw new Exception(string.Format("{0} from {1}", resource.SoeId, manager.SoeId), e);
                    }                   
                }
            }
        }

        //public string GetURL(string geid, bool matrix)
        //{
        //    var url = string.Empty;
        //    //var filePath = string.Empty;

        //    if (matrix)
        //        url = string.Format("http://gdir.nam.nsroot.net/Globaldir_New/GDIR_Download_Excel_Report.aspx?ReportName=DIRECT_MATRIX&Full_Name=name&Top_GEID={0}&ReportsToCount=99&Lang=ENGLISH", geid);
        //    //filePath = string.Format("{0}\\{1}.htm", @"\\lacbra001fs0010\DATA_GRP1\FTOOLS\Apps\Matrix\ExtractedFiles", geid);
        //    else
        //        url = string.Format("http://gdir.nam.nsroot.net/Globaldir_New/GDIR_Download_Excel_Report.aspx?ReportName=DIRECT_EMP&Full_Name=name&Top_GEID={0}&ReportsToCount=99&Lang=ENGLISH", geid);
        //    //filePath = string.Format("{0}\\_{1}.htm", @"\\lacbra001fs0010\DATA_GRP1\FTOOLS\Apps\Matrix\ExtractedFiles", geid);

        //    //if (!File.Exists(filePath))
        //    //{
        //    //    var webClient = new WebClient();
        //    //    webClient.DownloadFile(url, filePath);
        //    //}

        //    //return filePath;
        //    return url;
        //}

        public IEnumerable<RoutineParameter> Parameters
        {
            get { return null; }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
